package cn.wlinker.driver.common;

import cn.wlinker.driver.common.utils.IConnectHelper;
import cn.wlinker.driver.common.exception.NotFoundException;
import java.util.Map;

/**
 * 驱动抽象类
 *
 * @author gxsjx
 * @version 1.0
 * @date 2022/9/17
 * Copyright © wlinker.cn
 */
public abstract class AbstractDriver<C, T, R> implements IDriver<C, T, R> {

    protected Map<String, Object> connectionMap;

    protected IConnectHelper connectHelper;

    protected String getConnectionKey() {
        C connectionBean = getConnectionBean();
        return connectHelper.getConnectionKey(connectionBean);
    }

    public String getCacheKey() {
        C connectionBean = getConnectionBean();
        return connectHelper.getCacheKey(connectionBean);
    }

    public AbstractDriver(Map<String, Object> connectionMap) {
        this.connectionMap = connectionMap;
        afterCreated();
    }

    public AbstractDriver(Map<String, Object> connectionMap, IConnectHelper connectHelper) {
        this.connectionMap = connectionMap;
        this.connectHelper = connectHelper;
        afterCreated();
    }

    protected void afterCreated() {
        // do nothing
    }

    @Override
    public IConnectHelper getConnectHelper() {
        if (connectHelper == null) {
            throw new NotFoundException("未找到连接帮助类connectHelper");
        }
        return connectHelper;
    }

    @Override
    public Boolean open() throws Exception {
        C connectionBean = getConnectionBean();
        Object connect = getConnectHelper().getConnection(connectionBean);
        return connect != null && isOpen();
    }

    @Override
    public Boolean close() {
        C connectionBean = getConnectionBean();
        return getConnectHelper().disconnect(connectionBean);
    }

    @Override
    public Boolean isOpen() {
        C connectionBean = getConnectionBean();
        return getConnectHelper().isConnected(connectionBean);
    }
}
